package cas;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicStampedReference;

/**
 * @BelongsProject: concurrent
 * @BelongsPackage: cas
 * @Author: 江岸
 * @CreateTime: 2021-05-23 13:38
 * @Description: ABA问题 用
 */
public class ABAdemo {
    //对象，版本号
    public static AtomicStampedReference<Integer> a = new AtomicStampedReference(new Integer(0),1);

    public static void main(String[] args) {
        Thread main = new Thread(() -> {
            Integer expect = a.getReference();
            Integer newNum = expect + 1;
            Integer stamp = a.getStamp();
            Integer newStamp = stamp+1;
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            boolean b = a.compareAndSet(expect, newNum,stamp,newStamp);
            System.out.println(Thread.currentThread().getName() + b +a.getReference());
        });
        Thread other = new Thread(() -> {
            try {
                Thread.sleep(20);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            a.compareAndSet(a.getReference(), a.getReference()+1,a.getStamp(),a.getStamp()+1);
            System.out.println(Thread.currentThread().getName() +"num"+ a.getReference());
            a.compareAndSet(a.getReference(), a.getReference()+1,a.getStamp(),a.getStamp()+1);
            System.out.println(Thread.currentThread().getName() +"num"+ a.getReference());
        });
        main.start();
        other.start();
    }
}
